package com.tyijian.admin.core.exceptionHandle;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.authz.AuthorizationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.SimpleMappingExceptionResolver;
import org.springframework.web.servlet.view.json.MappingJackson2JsonView;

import com.tyijian.springside.core.JsonConstant;


/**
 * 捕捉所有服务异常信息，并把信息封装成json 返回
 * 
 * @author yangjp
 *
 */
@Component
public class RestMappingExceptionResolver extends SimpleMappingExceptionResolver {

	private static final Logger logger = LoggerFactory.getLogger(RestMappingExceptionResolver.class);
	
	@Override
	protected ModelAndView doResolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
		ModelAndView mv = super.doResolveException(request, response, handler, ex);
		logger.error(ex.getMessage());
		ex.printStackTrace();
        if (mv == null) {
            Map<String, String> params = new HashMap<>();
        	int status = 0;
        	if (ex instanceof AuthorizationException) { //捕捉Shiro的权限Exception
        		params.put(JsonConstant.ERRMSG, "用户没有访问权限，请联系管理员");
    			status = HttpStatus.UNAUTHORIZED.value();
    		} else {
        		params.put(JsonConstant.ERRMSG, "服务器异常，请稍后再试");
    			status = HttpStatus.INTERNAL_SERVER_ERROR.value();
    		}
            super.applyStatusCodeIfPossible(request, response, status);
            return new ModelAndView(new MappingJackson2JsonView(), params);
        }
        return mv;
	}
}
